﻿
<!--
https://github.com/netnr
https://gitee.com/netnr
https://www.netnr.com
https://zme.ink
-->


<!DOCTYPE html>
<html>
<head>

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <link rel='shortcut icon' href='/favicon.ico' type='image/x-icon' />


    <title>JSON转换XML 脚本服务</title>

    <meta name="keywords" content="netnr NET牛人 JSON转换XML" />
    <meta name="description" content="Script Services JSON与XML相互转换" />

</head>
<body>
<div id='LoadingMask' style='position:fixed;top:0;left:0;bottom:0;right:0;background-color:white;z-index:19999;background-image:url('/images/loading.svg');background-repeat:no-repeat;background-position:48% 45%'></div>
<link href='https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css' rel='stylesheet'>
<link href='https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css' rel='stylesheet'>
<script src='https://cdn.jsdelivr.net/npm/jquery@3.5.0/dist/jquery.min.js'></script>
<script src='https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js'></script>
<script src='https://cdn.jsdelivr.net/npm/jzjs@2.0.2/2.0.2/jz.min.js'></script>
<link href='https://cdn.jsdelivr.net/npm/netnrnav@1.1.0/src/netnrnav.css' rel='stylesheet' />
<script src='https://cdn.jsdelivr.net/npm/netnrnav@1.1.0/src/netnrnav.js' defer async></script>

<script>
    $.ajax({
        url: '/images/icon.svg?20201228',
        dataType: 'text',
        success: function (data) {
            $('body').append('<div class="d-none">' + data + '</div>')
        }
    })
</script>

        <link href="/css/global.css?v=YuzFOH_Z7ma5bs-3HMdZQu0aPQZ1pkBqrzQ_Ri8Yh3k" rel="stylesheet" />
        <script src="/js/global.js?v=ckkNo3hER74SKnNCuouMgEfxEpEMP3phtPl9uA0_Lnc"></script>
            <!--导航-->
            <button type="button" class="MenuToggle show-in-mobile btn btn-primary ml-3 mt-3">
                <span class="fa fa-align-justify fa-2x"></span>
            </button>
            <div class="netnrnav horizontal">
                <div class="netnrnav-wrapper">
                    <ul>
                        <li><a href="https://www.netnr.com" class="siteIcon"><img src="/favicon.svg" /> 首页</a></li>
                        <li><a href="https://www.netnr.com/gist/discover" title="代码片段"><span class="fa fa-fw fa-file-code-o"></span> Gist</a></li>
                        <li><a href="https://www.netnr.com/run/discover" title="在线运行代码"><span class="fa fa-fw fa-play"></span> Run</a></li>
                        <li><a href="https://www.netnr.com/doc" title="文档管理"><span class="fa fa-fw fa-book"></span> Doc</a></li>
                        <li><a href="https://www.netnr.com/draw/discover" title="绘制"><span class="fa fa-fw fa-paint-brush"></span> Draw</a></li>
                        <li><a href="/" title="ss.js.org"><span class="fa fa-fw fa-wrench"></span> 服务</a></li>
                        <li style="background-image: radial-gradient(ellipse, white, rgb(227, 248, 240))">
                            <!--标题-->
                                <a href='javascript:location.reload(false)' title="JSON与XML相互转换">
                                    <svg class="titleicon"><use xlink:href="#xml"></use></svg> JSON&#x8F6C;&#x6362;XML
                                </a>
                        </li>
                        <li>
                            <a class="text-muted"><span class="fa fa-fw fa-ellipsis-h"></span></a>
                            <ul>
                                <li><a target="_blank" title="码云" href="https://gitee.com/netnr"><i class="fa fa-fw fa-git"></i> Gitee <sup><i class="fa small fa-external-link"></i></sup></a></li>
                                <li><a target="_blank" title="GitHub" href="https://github.com/netnr"><i class="fa fa-fw fa-github"></i> GitHub <sup><i class="fa small fa-external-link"></i></sup></a></li>
                            </ul>
                        </li>
                    </ul>
                </div>
            </div>
        <div class="min300 mt-3">
            <div class="container-fluid">
    <div class="row" id="tobox">
        <div class="col-sm-6">
            <div class="input-group mb-2">
                <button type="button" class="btn btn-warning" id="btnToXml">JSON → XML</button>
                <div class="input-group-prepend">
                    <select class="custom-select" id="seautoformatter1">
                        <option value="1">自动格式化</option>
                        <option value="2">不格式化</option>
                    </select>
                </div>
            </div>
            <pre id="txt1" class="border overflow-hidden">
{
  "site": {
    "title": "NET牛人",
    "domain": "https://www.netnr.com",
    "foreverdomain": "http://netnr.top",
    "createtime": "2014.01.01",
    "qqgroup": 83084426
  },
  "about": {
    "name": "netnr",
    "sex": "男",
    "birthday": "1992.07.13",
    "injob": "2012.03.01",
    "live": "中国重庆",
    "stain": null,
    "qq": 1041911384,
    "mail": "netnr@netnr.com",
    "git": [
      {
        "name": "github",
        "url": "https://github.com/netnr"
      },
      {
        "name": "gitee",
        "url": "https://gitee.com/netnr"
      }
    ]
  },
  "updaet": "2018.01.08",
  "version": "v.1.0.0"
}</pre>
        </div>
        <div class="col-sm-6">
            <div class="input-group mb-2">
                <button type="button" class="btn btn-warning" id="btnToJson">XML → JSON</button>
                <div class="input-group-prepend">
                    <select class="custom-select" id="seautoformatter2">
                        <option value="1">自动格式化</option>
                        <option value="2">不格式化</option>
                    </select>
                </div>
                <div class="input-group-prepend">
                    <i class="fa fa-info-circle ml-2" data-toggle="tooltip" title="必须有一个根节点，没有则自动加 root"></i>
                </div>
            </div>

            <div class="border overflow-hidden" id="txt2"></div>
        </div>
    </div>
</div>

<script>
    function AutoHeight() {
        var ch = $(window).height() - $('#txt1').offset().top - 15;
        $('#txt1').css('height', Math.max(200, ch));
        $('#txt2').css('height', Math.max(200, ch));
    }
    AutoHeight();
</script>

<script src='https://cdn.jsdelivr.net/gh/abdolence/x2js@1.2.0/xml2json.min.js'></script>
<script src='https://cdn.jsdelivr.net/npm/monaco-editor@0.21.2/min/vs/loader.js'></script>

<script>
    require.config({
        paths: {
            vs: 'https://cdn.jsdelivr.net/npm/monaco-editor@0.21.2/min/vs'
        },
        'vs/nls': { availableLanguages: { '*': 'zh-cn' } }
    });
</script>



<script>
    var editor1, editor2;

    require(['vs/editor/editor.main'], function () {

        var txt1 = document.getElementById('txt1');
        var tv1 = txt1.innerHTML;
        txt1.innerHTML = '';

        editor1 = monaco.editor.create(txt1, {
            value: tv1,
            language: 'json',
            scrollBeyondLastLine: false,
            automaticLayout: true,
            theme: 'vs',
            scrollbar: {
                verticalScrollbarSize: 6,
                horizontalScrollbarSize: 6
            },
            minimap: {
                enabled: false
            }
        });

        editor1.onDidChangeModelContent(function (e) {
            if ($('#seautoformatter1').val() == "1") {
                window.clearTimeout(window.defer1)
                window.defer1 = setTimeout(function () {
                    try {
                        if (window.very1 == 'self') {
                            window.very1 = '';
                        } else {
                            var val = JSON.stringify(JSON.parse(editor1.getValue()), null, 2);
                            window.very1 = 'self';
                            editor1.setValue(val);
                        }
                    } catch (e) { }
                }, 20)
            }
        });

        editor2 = monaco.editor.create($("#txt2")[0], {
            value: '',
            language: 'xml',
            automaticLayout: true,
            scrollBeyondLastLine: false,
            theme: 'vs',
            scrollbar: {
                verticalScrollbarSize: 6,
                horizontalScrollbarSize: 6
            },
            minimap: {
                enabled: false
            }
        });

        editor2.onDidChangeModelContent(function (e) {
            if ($('#seautoformatter2').val() == "1") {
                window.clearTimeout(window.defer2)
                window.defer2 = setTimeout(function () {
                    try {
                        if (window.very2 == 'self') {
                            window.very2 = '';
                        } else {
                            var val = formatXml(editor2.getValue());
                            window.very2 = 'self';
                            editor2.setValue(val);
                        }
                    } catch (e) { }
                }, 20);
            }
        });
    });

    $(window).resize(AutoHeight);

    $("#btnToJson").click(function (e) {
        var x2js = new X2JS({
            attributePrefix: "@"
        });
        var xmlText = editor2.getValue();
        if (xmlText == "") {
            jz.msg('XML 不能为空');
            return false;
        }
        var jsonObj = x2js.xml_str2json(xmlText);
        if (jsonObj == null && $(xmlText).length) {
            xmlText = '<root>' + xmlText + '</root>';
            jsonObj = x2js.xml_str2json(xmlText);
        }
        if (jsonObj == null) {
            jz.msg('转换错误');
            return false;
        }

        editor1.setValue(JSON.stringify(jsonObj));
    });

    $("#btnToXml").click(function () {
        var x2js = new X2JS({
            attributePrefix: "@"
        });
        var jsonText = editor1.getValue();
        if (jsonText == "") {
            jz.msg('JSON 不能为空');
            return false;
        }
        var jsonObj = $.parseJSON(jsonText);
        var xmlAsStr = x2js.json2xml_str(jsonObj);

        editor2.setValue(xmlAsStr);
    });

    function formatXml(xml) {
        var formatted = '';
        var reg = /(>)(<)(\/*)/g;
        xml = xml.replace(reg, '$1\r\n$2$3');
        var pad = 0;
        jQuery.each(xml.split('\r\n'), function (index, node) {
            var indent = 0;
            if (node.match(/.+<\/\w[^>]*>$/)) {
                indent = 0;
            } else if (node.match(/^<\/\w/)) {
                if (pad != 0) {
                    pad -= 1;
                }
            } else if (node.match(/^<\w[^>]*[^\/]>.*$/)) {
                indent = 1;
            } else {
                indent = 0;
            }

            var padding = '';
            for (var i = 0; i < pad; i++) {
                padding += '  ';
            }

            formatted += padding + node + '\r\n';
            pad += indent;
        });

        return formatted;
    }

    //提示
    $('.fa-info-circle').tooltip();
</script>
        </div>
        <a href="javascript:ss.toTop();" class="totop" title="返回顶部">ˆ</a>
</body>
</html>
